<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条区域 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab栏区域 -->
      <el-form
        :model="addForm"
        :rules="addFormrules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
        class="demo-ruleForm"
      >
        <el-tabs
          :tab-position="'left'"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品介绍" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="{
                  label: 'cat_name',
                  value: 'cat_id',
                  children: 'children'
                }"
                @change="handleChange"
                clearable
                :show-all-levels="false"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染表单item项 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTableData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="cb"
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableData"
              :key="item.attr_id"
              border
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 图片上传地址 action 表示图片上传到后台的API地址-->
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headers"
              :on-success="handelSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.goods_introduce">
            </quill-editor>
            <el-button type="primary" class="btnAdd" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
<!-- 图片展示框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewDialogVisible"
      width="50%"
    >
     <img :src="previewPath" alt="" class="previewImg" />
    </el-dialog>
  
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      activeIndex: '0',
      /* 商品分类列表 */
      cateList: [],
      /* 添加商品表单 */
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        /* 选中的商品分类id数组 */
        goods_cat: [],
        /* 上传图片列表 */
        pics: [],
        /* 商品详情介绍 */
        goods_introduce: '',
        /* 商品参数数组 包含 静态参数 和 动态参数 */
        attrs: []
      },
      // 表单验证规则
      addFormrules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请输入商品分类', trigger: 'blur' }
        ]
      },
      /* 动态参数 */
      manyTableData: [],
      /* 静态参数 */
      onlyTableData: [],
      /* 上传图片URL地址 */
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      /* 图片上传头部设置 */
      headers: {
        Authorization: window.sessionStorage.getItem('token')
      },
      /* 预览图片地址 */
      previewPath: '',
      /* 图片展示框 */
      previewDialogVisible: false,
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    /* 获取分类数据 */
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status != 200) {
        return this.$message.error('获取分类数据失败')
      }
      this.cateList = res.data
      console.log(this.cateList)
    },
    /* 级联选择器选中项变化，会触发这个函数 */
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    /* 切换对应标签回调方法 */
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName == '0' && this.addForm.goods_cat.length !== 3) {
        this.$message({
          type: 'error',
          message: '请先选择商品分类'
        })
        return false
      }
    },
    /* tab 被选中时触发 */
    async tabClicked() {
      console.log(this.activeIndex)
      console.log('分类id', this.cateId)
      if (this.activeIndex === '1') {
        // 访问动态参数
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' }
          }
        )
        if (res.meta.status !== 200) {
          return this.$message({
            type: 'error',
            message: '获取商品参数失败!'
          })
        }
        console.log('商品参数列表', res.data)
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.lenght === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTableData = res.data
      } else if (this.activeIndex === '2') {
        // 商品属性
        const {
          data: res
        } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'only' }
        })
        if (res.meta.status !== 200) {
          return this.$message.error('获取静态属性失败!')
        }
        console.log(res.data)
        this.onlyTableData = res.data
      }
    },
    /* 图片预览 */
    handlePreview() {},
    /* 移除图片操作 */
    handleRemove(file) {
      console.log('上传的文件', file)
      // 1、获取将要删除的图片的临时路径
      const filePath = file.response.data.tmp_path
      // 2、 从 pic 数组中，找到这个图片对应的索引值
      const i = this.addForm.pics.findIndex(item => {
        item.pic === filePath
      })
      // 3、调用数组的 splice 方法，，把图片信息对象从数组中移除
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm)
    },
    /* 图片上传成功钩子函数 */
    handelSuccess(response) {
      console.log(response)
      // 拼接
      const picInfo = { pic: response.data.tmp_path }
      // 2、将图片信息对象，push到pics数组中
      this.addForm.pics.push(picInfo)
      console.log(picInfo)
    },
    /* 处理图片预览效果 */
    handlePreview(file) {
      /* 拿到图片地址 */
      this.previewPath = file.response.data.url
      this.previewDialogVisible = true
      console.log(file)
    },
    /* 添加商品 */
    add () {
      console.log(this.addForm)
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写必要的表单项!')
        }
         // 执行添加的业务逻辑
         /* 级联选择器 v-model 绑定的是数组，
         如果使用了join进行拆分的话，那么数组就会变成字符串
         ，级联选择器出错，因此使用这个loadsh 深拷贝 */
         const form = _.cloneDeep(this.addForm)
         form.goods_cat = form.goods_cat.join(',')
         // 拿到动态参数的 id 和 value 保存到数组中
         this.manyTableData.forEach(item => {
           const newInfo = {
             attr_id: item.attr_id,
             attr_value: item.attr_vals.join(' ')
           }
           this.addForm.attrs.push(newInfo)
         })
         /* 静态属性 */
         this.onlyTableData.forEach(item => {
           const newInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals
           }
           this.addForm.attrs.push(newInfo)
         })
         form.attrs = this.addForm.attrs
         const { data: res} = await this.$http.post('goods',form)
         if (res.meta.status !== 201) {
           return this.$message.error('添加商品失败!')
         }
         this.$message.success('添加商品成功!')
         this.$router.push('/goods')
      })
    }
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2] * 1
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 5px 0 0 !important;
}
.previewImg {
  width: 100%;
}
.btnAdd {
  margin-top: 15px;
}
</style>